//
//  AddLicensePlateViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/8/1.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "AddLicensePlateViewController.h"
#import "PLTextView.h"
#import "ImageSelectEditorView.h"
#import "SelectDateView.h"
#import "SelectAddressView.h"
#import "SellSelectTypeViewController.h"

@interface AddLicensePlateViewController ()<UITextFieldDelegate,UITextViewDelegate,SelectDateViewDelegate,SelectAddressViewDelegate>{
    UIScrollView *scrollBG;
    UITextField *txtMoney;//价格
    UITextField *txtLevle;//等级
    UITextField *txtName;
    UITextField *txtcapital;//资本
    UITextField *txtCity;
    UITextField *txtAddress;
    UITextField *txtStartDate;
    UITextField *txtEndDate;
    UITextField *txtRange;//经营范围
    PLTextView *txtadvantage;//转让优势
    ImageSelectEditorView *imageEditorV;
    
    NSInteger tempY;
    SelectDateView *dateView;
    SelectDateView *dateView2;
    
    NSString *selectDate;
    NSString *selectDateEnd;
    
    SelectAddressView *selectCity;
    NSDictionary * dicP1City;
    NSDictionary * dicP2City;
    NSDictionary * dicP3City;
    NSArray *arrayCity;
    
    NSDictionary *dicSelectLevel;
    
}

@end

@implementation AddLicensePlateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    scrollBG=[[UIScrollView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight-44)];
    scrollBG.backgroundColor=rgbGray;
    scrollBG.autoresizingMask=UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:scrollBG];
    
    UIButton *btnSub=[RHMethods buttonWithFrame:CGRectMake(0, YH(scrollBG), kScreenWidth, 44) title:@"发布" image:nil bgimage:nil];
    [btnSub setBackgroundColor:rgbpublicColor];
    [btnSub setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnSub addTarget:self action:@selector(subButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSub];
    
    tempY=10;
    txtMoney=[self addViewWithFrameY:tempY withTitle:@"结算价格" withSel:nil];
    tempY+=44;
    txtLevle=[self addViewWithFrameY:tempY withTitle:@"产品等级" withSel:@selector(selectLevleButtonClicked)];
    tempY+=44+10;
    
    txtName=[self addViewWithFrameY:tempY withTitle:@"公司名称" withSel:nil];
    tempY+=44;
    txtcapital=[self addViewWithFrameY:tempY withTitle:@"注册资本" withSel:nil];
    tempY+=44;
    txtCity=[self addViewWithFrameY:tempY withTitle:@"注册地址" withSel:@selector(selectCityButtonClicked)];
    tempY+=44;
    txtAddress=[self addViewWithFrameY:tempY withTitle:@"详细地址" withSel:nil];
    tempY+=44+10;
    
    
    txtStartDate=[self addViewWithFrameY:tempY withTitle:@"成立时间" withSel:@selector(selectStartDateButtonClicked)];
    tempY+=44;
    txtEndDate=[self addViewWithFrameY:tempY withTitle:@"到期时间" withSel:@selector(selectEndDateButtonClicked)];
    tempY+=44;
    txtRange=[self addViewWithFrameY:tempY withTitle:@"经营范围" withSel:nil];
    tempY+=44;
    UIView *viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, tempY, kScreenWidth, 110)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [scrollBG addSubview:viewBG];
    txtadvantage=[[PLTextView alloc] initWithFrame:CGRectMake(10, tempY+5, kScreenWidth-20, 100)];
    txtadvantage.delegate=self;
    txtadvantage.Placeholder=@"转让优势";
    [scrollBG addSubview:txtadvantage];
    tempY+=110;
    [self initImagesView];
    
    if ([self.userInfo isEqualToString:@"Edit"]) {
        dicSelectLevel=@{@"id":[self.otherInfo valueForJSONStrKey:@"levelid"]};
        txtName.text=[self.otherInfo valueForJSONStrKey:@"title"];
        txtMoney.text=[self.otherInfo valueForJSONStrKey:@"price"];
        txtLevle.text=[self.otherInfo valueForJSONStrKey:@"levelname"];
        txtcapital.text=[self.otherInfo valueForJSONStrKey:@"regcapital"];
        txtAddress.text=[self.otherInfo valueForJSONStrKey:@"address"];
        txtStartDate.text=[self.otherInfo valueForJSONStrKey:@"regtime"];
        txtEndDate.text=[self.otherInfo valueForJSONStrKey:@"expiretime"];
        txtRange.text=[self.otherInfo valueForJSONStrKey:@"businessscope"];
        txtadvantage.text=[self.otherInfo valueForJSONStrKey:@"advantage"];
        
        dicP1City=@{@"areaid":[self.otherInfo valueForJSONStrKey:@"province"],@"parentid":@"0"};
        dicP2City=@{@"areaid":[self.otherInfo valueForJSONStrKey:@"city"],@"parentid":[self.otherInfo valueForJSONStrKey:@"province"]};
        dicP3City=@{@"areaid":[self.otherInfo valueForJSONStrKey:@"area"],@"parentid":[self.otherInfo valueForJSONStrKey:@"city"]};
        txtCity.text=[self.otherInfo valueForJSONStrKey:@"regaddress"];//[NSString stringWithFormat:@"%@ %@ %@",[dicP1City valueForJSONStrKey:@"name"],[dicP2City valueForJSONStrKey:@"name"],[dicP3City valueForJSONStrKey:@"name"]];
        __weak UIScrollView *viewS=scrollBG;
        [imageEditorV setImageUrlArray:[self.otherInfo objectForJSONKey:@"path"] imageChange:^(NSInteger suc,CGFloat h) {
            viewS.contentSize=CGSizeMake(kScreenWidth-1, YH(imageEditorV)>H(viewS)+1?YH(imageEditorV):H(viewS)+1);
        }];
    }else{
        dicSelectLevel=@{};
        __weak UIScrollView *viewS=scrollBG;
        [imageEditorV setImageUrlArray:@[] imageChange:^(NSInteger suc,CGFloat h) {
            viewS.contentSize=CGSizeMake(kScreenWidth-1, YH(imageEditorV)>H(viewS)+1?YH(imageEditorV):H(viewS)+1);
        }];
    }
    
}
-(void)initImagesView{
    imageEditorV=[[ImageSelectEditorView alloc] initWithFrame:CGRectMake(0, tempY, kScreenWidth, 10)];
    [scrollBG addSubview:imageEditorV];
    imageEditorV.maxNumber=9;
   
    
}

-(UITextField *)addViewWithFrameY:(float)_fy withTitle:(NSString *)strTitle withSel:(SEL)sel{
    UIView *viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, _fy, kScreenWidth, 44)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [scrollBG addSubview:viewBG];
    
    [viewBG addSubview:[RHMethods labelWithFrame:CGRectMake(10, 0, 80, H(viewBG)) font:fontTitle color:rgbTitleColor text:strTitle]];
    
//    [viewBG addLineLayerWhitframe:CGRectMake(0, 0, W(viewBG), 0.5) whitColor:rgbLineColor];
    [viewBG addLineLayerWhitframe:CGRectMake(0, 43.5, W(viewBG), 0.5) whitColor:rgbLineColor];
    UITextField *txt=[RHMethods textFieldlWithFrame:CGRectMake(90, 0, W(viewBG)-100, 44) font:fontTitle color:rgbTitleColor placeholder:@"请输入" text:@"" ];
    [txt setTextAlignment:NSTextAlignmentRight];
    txt.delegate=self;
    [viewBG addSubview:txt];
    if (sel) {
        txt.placeholder=@"请选择";
        txt.enabled=NO;
        txt.frameWidth=W(viewBG)-117;
        UIButton *btnSelect=[RHMethods buttonWithFrame:viewBG.bounds title:nil image:@"Righticon070116" bgimage:nil];
        [btnSelect setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [btnSelect setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
        [btnSelect addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
        [viewBG addSubview:btnSelect];
    }
    return txt; 
}

#pragma mark button
-(void)subButtonClicked{
    
    NSString *strName=txtName.text;
    NSString *strMoeny=txtMoney.text;//价格
//    NSString *strLevle=txtLevle.text;//等级
    NSString *strCapital=txtcapital.text;//资本
    NSString *strCity=txtCity.text;
    NSString *strAddress=txtAddress.text;
    NSString *strStartDate=txtStartDate.text;
    NSString *strEndDate=txtEndDate.text;
    NSString *strRange=txtRange.text;//经营范围
    NSString *strNote=txtadvantage.text;//转让优势
   
    
    if (![strName notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入公司名称"];
        return;
    }
    if (![strMoeny notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入结算价格"];
        return;
    }
    if (![strCapital notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入资本"];
        return;
    }
    if (![strCity notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"选择注册地址"];
        return;
    }
    if (![strAddress notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入详细地址"];
        return;
    }
    if (![strStartDate notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请选择成立时间"];
        return;
    }
    if (![strEndDate notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请选择到期时间"];
        return;
    }
    if (![strRange notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入经营范围"];
        return;
    }
    
    krequestParam
    [dictparam setValue:strName forKey:@"title"];
    [dictparam setValue:strMoeny forKey:@"price"];
    [dictparam setValue:[dicSelectLevel valueForJSONStrKey:@"id"] forKey:@"level"];
    [dictparam setValue:strCapital forKey:@"regcapital"];
//    [dictparam setValue:strCity forKey:@"regaddr"];
    [dictparam setValue:strAddress forKey:@"address"];
    [dictparam setValue:strStartDate forKey:@"regtime"];
    [dictparam setValue:strEndDate forKey:@"expiretime"];
    [dictparam setValue:strRange forKey:@"businessscope"];
    [dictparam setValue:strNote forKey:@"advantage"];
    if ([[dicP3City valueForJSONStrKey:@"areaid"] notEmptyOrNull]) {
        [dictparam setValue:[dicP3City valueForJSONStrKey:@"areaid"] forKey:@"regaddr"];
    }else{
        [dictparam setValue:[dicP2City valueForJSONStrKey:@"areaid"] forKey:@"regaddr"];
    }
    
    if ([self.userInfo isEqualToString:@"Edit"]  ) {
        if ( [imageEditorV.arrayDeleteIds count]>0) {
            [dictparam setValue:[imageEditorV.arrayDeleteIds componentsJoinedByString:@","] forKey:@"pathid"];
        }
        [dictparam setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"id"];
    }
    NSArray *arrayImages=[imageEditorV getRequsetArrywithkey:@"path" removeServer:YES];
    [NetEngine uploadAllFileAction:XKFV4productsupdateproducts withParams:dictparam fileArray:arrayImages onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            [self backRefreshData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [super backButtonClicked:nil];
            });
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    } onError:^(NSError *error) {
        [SVProgressHUD showImage:nil status:alertErrorTxt];
    } withMask:SVProgressHUDMaskTypeBlack];
    

    
}
-(void)selectLevleButtonClicked{
    [self pushController:[SellSelectTypeViewController class] withInfo:NSStringFromClass([self class]) withTitle:@"选择等级" withOther:@{@"selectArray":@[[dicSelectLevel valueForJSONStrKey:@"id"]],@"list":[[[Utility Share] userTypeData] objectForJSONKey:@"level"]}];
}
-(void)selectCityButtonClicked{
//    [SVProgressHUD showImage:nil status:@"地址"];
    //SelectAddressView
    if (arrayCity) {
        if (!selectCity) {
            selectCity=[[SelectAddressView alloc] init];
        }
        selectCity.delegate=self;
        selectCity.dicP1=dicP1City;
        selectCity.dicP2=dicP2City;
        selectCity.dicP3=dicP3City;
        selectCity.arrayAddress=arrayCity;
        [selectCity show];
    }else{
        [self loadCityData];
    }
    
}
-(void)loadCityData{
    krequestParam
    [NetEngine createPostAction:XKFV4customerproductcity withParams:dictparam onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            arrayCity=[[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"];
            [self selectCityButtonClicked];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
}
-(void)selectStartDateButtonClicked{
    //选择时间
    if (!dateView) {
        dateView=[[SelectDateView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    }
    dateView.strType=@"date";
    dateView.delegate=self;
    [dateView show];
}
-(void)selectEndDateButtonClicked{
    //选择时间
    if (!dateView2) {
        dateView2=[[SelectDateView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    }
    dateView2.strType=@"date";
    dateView2.delegate=self;
    [dateView2 show];
}
#pragma mark UITextFieldDelegate,UITextViewDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark SelectDateViewDelegate
-(void)select:(SelectDateView *)sview object:(id)dic{
    // dateTemp=dic;
    if (sview==dateView) {
        selectDate=[NSString stringWithFormat:@"%f",[dic timeIntervalSince1970]];
        txtStartDate.text=[[Utility Share] time_ChangeTheFormat:selectDate];
    }else{
        selectDateEnd=[NSString stringWithFormat:@"%f",[dic timeIntervalSince1970]];
        txtEndDate.text=[[Utility Share] time_ChangeTheFormat:selectDateEnd];
    }
   
}
#pragma mark SelectAddressViewDelegate
-(void)selectPicker:(SelectAddressView *)selectView address1:(id)addres_a address2:(id)address_b address3:(id)address_c{
    dicP1City=addres_a;
    dicP2City=address_b?address_b:@{};
    dicP3City=address_c?address_c:@{};
    txtCity.text=[NSString stringWithFormat:@"%@ %@ %@",[dicP1City valueForJSONStrKey:@"name"],[dicP2City valueForJSONStrKey:@"name"],[dicP3City valueForJSONStrKey:@"name"]];
}

#pragma mark pop
-(void)backRefreshData{
    for (id controller in self.navigationController.viewControllers) {
        if ([NSStringFromClass([controller class]) isEqualToString:@"CRMViewController"]||
            [NSStringFromClass([controller class]) isEqualToString:@"UserLicensePlateViewController"]) {
            if ([(NSObject*)controller respondsToSelector:@selector(popRefreshData)]) {
                [controller performSelector:@selector(popRefreshData) withObject:nil afterDelay:0.01];
            }
            continue;
        }
    }
    
}
-(void)popRefreshType:(NSDictionary *)dic{
    dicSelectLevel=dic;
    txtLevle.text=[dic valueForJSONStrKey:@"name"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
